#!/usr/bin/python

# Copyright (c) 2011 Michael Mol <mikemol@gmail.com>.
#
# This work is licensed under a
# Creative Commons Attribution 3.0 Unported License, viewable at
# http://creativecommons.org/licenses/by/3.0/
#
import pickle as pickle

def deserialize(filename, default):
    """Takes the filename of a pickle file and a value to which to default.
    
    If the pickle fails to deserialize, returns the default value.
    Otherwise, returns the deserialized pickle."""
    ret = default
    try:
        wfile = open(filename, "rwb")
        try:
            ret = pickle.load(wfile)
        except:
            print filename + " corrupt or empty"
        try:
            wfile.close()
        except:
            print "Could not close " + filename + " after reading"
    except:
        print "Failed to open " + filename 
    return ret

def serialize(filename, obj):
    """Takes a filename and an object. Pickles object, stores in file.
    
    No return value."""
    try:
        wfile = open(filename, "wb")
        try:
            pickle.dump(obj, wfile, -1)
        except:
            print "Failed to pickle object"
        try:
            wfile.close()
        except:
            print "Failed to close " + filename
    except:
        print "Failed to open " + filename + " for storage"

